  /*
  * MinIO Cloud Storage (C) 2018 MinIO, Inc.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
  *
  *     http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */

  import React from "react";
  import { connect } from "react-redux"
  import { createStyles, makeStyles, withStyles, Theme } from '@material-ui/core/styles';
  import FormControl from '@material-ui/core/FormControl';
  import InputLabel from '@material-ui/core/InputLabel';
  import MenuItem from '@material-ui/core/MenuItem';
  import Select from '@material-ui/core/Select';
  import InputBase from '@material-ui/core/InputBase';
  import ReactEcharts from 'echarts-for-react';
  import Typography from "@material-ui/core/Typography";
  import Alert from '@material-ui/lab/Alert';
  import IconButton from '@material-ui/core/IconButton';
  import Collapse from '@material-ui/core/Collapse';
  import CloseIcon from '@material-ui/icons/Close';
  import api from "../../../common/api";
  import { ChartUrl, AllQueryUrl, timeConvert, beforeNowtimeByMinu } from "./types";

  const BootstrapInput = withStyles((theme: Theme) =>
  createStyles({
    root: {
      'label + &': {
        marginTop: 0,
        marginLeft: theme.spacing(4),
      },
    },
    input: {
      borderRadius: 4,
      position: 'relative',
      backgroundColor: theme.palette.background.paper,
      border: '1px solid #ced4da',
      fontSize: 14,
      padding: '3px 26px 3px 12px',
      transition: theme.transitions.create(['border-color', 'box-shadow']),
      '&:focus': {
        borderRadius: 4,
        borderColor: '#80bdff',
        boxShadow: '0 0 0 0.2rem rgba(0,123,255,.25)',
      },
    },
  }),
)(InputBase);
const styles = (theme: Theme) =>
  createStyles({
    alert: {
      position: "absolute",
      width: "100%",
      textAlign: "center",
      zIndex: 1000, 
      top: 35
    },
    alertPop: {
      margin: "0 auto",
      width: "160px"
    },
    chart: {
      height: '337px', 
      width: '100%', 
      marginTop: -25,
      marginBottom: -40
    },
    selItem: {
      width: "90%",
      paddingLeft: "5%",
      flexDirection: "row",
      zIndex: 1001
    },
    selType: {
      whiteSpace: "nowrap",
      lineHeight: "24px",
      fontSize: 14
    },
});
interface ChartState {
  classes: any;
  inputStep: string,
}
export class ChartA extends React.Component<any, any> {
  constructor(props:any){
    super(props);
    this.state = {
      records: [],
      xrecord:[],
      legend:[],
      recordsData:[],
      queryData:[],
      type:"",
      loading: false,
      step: "14",
      dataWarn:"",
      open: false
    };
  };
  setOpen(a:boolean){
    this.setState({
      open: a
    })
  }
  // getChart(type:string, step:any) {
    getChart(type:string) {
    let duration = 60;
    // if(step == '1'){
    //   duration = 15
    // }else if(step == '7'){
    //   duration = 30
    // }else if(step == '14'){
    //   duration = 60
    // }else if(step == '28'){
    //   duration = 120
    // }else if(step == '86'){
    //   duration = 360
    // }else if(step == '172'){
    //   duration = 720
    // }else if(step == '345'){
    //   duration = 1440
    // }
    let url = ChartUrl+type+"&start="+Date.parse(beforeNowtimeByMinu(duration)).toString().substring(0,10)+"&end="+Date.parse(beforeNowtimeByMinu(0)).toString().substring(0,10)+"&step=14";
    api
      .invoke("GET", url)
      .then((res) => {
        var xrec = new Array();
        var rootData = res.data.result;
        if(rootData != []){
          for(var i=0;i<rootData.length;i++){
            for(var a=0;a<rootData[i].values.length;a++){
              rootData[i].values[a][0] = timeConvert(parseInt(rootData[i].values[a][0]));
            }
          }
          var data = rootData[0].values;
          for(var n=0;n<data.length;n++){
            xrec[n]=data[n][0]
          }
          let leg = rootData.map(function (item:any) {
            return item.metric.job +": "+ item.metric.instance;
          })
          let recData = rootData.map(function (item:any) {
            return {
              name: item.metric.job +": "+ item.metric.instance,
              type: 'line',
              data: item.values.map(function (this: any, itemx:any) {
                return [itemx[0], parseFloat(itemx[1])]
              })
            }
          })
          this.setState({
            legend: leg,
            xrecord: xrec,
            recordsData: recData,
          });
        }else{
          this.setState({
            dataWarn: "暂无数据",
            loading: false 
          })
          this.setOpen(true);
        }
      })
      .catch(err => {
        this.setState({
          dataWarn: "暂无数据",
          loading: false 
        })
        this.setOpen(true);
      });
  }
    getQueryUrl(){
      api
        .invoke("GET", AllQueryUrl)
        .then((res) => {
          if(res.status == "success"){
            this.setState({
              queryData: res.data
            })
          }else{
          }
        })
        .catch(err => {
          this.setState({
            dataWarn: "暂无数据",
            loading: false 
          })
          this.setOpen(true);
        });
  }
  componentDidMount(): void {
    this.setState({
      step: "14",
    })
    var that = this
    if(that.state.type != ""){
      that.getChart(that.state.type);
      // that.getChart(that.state.type, that.state.step);
    }
    that.getQueryUrl();
  }
  // componentDidUpdate(prevProps:any): void {
  //   if(prevProps.inputStep !== this.state.step){
  //     this.getChart(this.state.type, this.state.step);
  //       var timer = setInterval(() => {
  //         let url = window.location.href
  //         if(this.state.type != ""){
  //           if(url.indexOf("/dashboard") != -1){
  //             console.log("AA= "+this.state.step)
  //             this.getChart(this.state.type, this.state.step);
  //           }else{
  //             clearInterval(timer)
  //           }
  //         }
  //       }, 25000)
  //   }
  // }
  // static getDerivedStateFromProps(nextProps:any, prevState:any) {
  //   // 当传入的type发生变化的时候，更新state
  //   if (nextProps.inputStep !== prevState.step) {
  //     return {
  //       step: nextProps.inputStep
  //     }
  //   }
  //   console.log(prevState.step)
  //   // 否则，对于state不进行任何操作
  //   return null;
  // }
  getOption= () => ({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'cross'
        },
        backgroundColor: 'rgba(245, 245, 245, 0.8)',
        borderWidth: 1,
        borderColor: '#ccc',
        padding: 10,
        textStyle: {
            color: '#000'
        },
    },
      legend: {
        type: 'scroll',
        orient: 'vertical',
        top: 20,
        right: 0,
        height:60,
        data: this.state.legend
      },
      xAxis: {
          data: this.state.xrecord
      },
      yAxis: {
        splitLine: {
          show: true
        }
      },
      series: this.state.recordsData
  });
  render() {
    const { classes } = this.props;
    // var handleChange = (event: React.ChangeEvent<{ value: unknown }>) => {
    //   this.setState({ 
    //     step: event.target.value
    //   });
    //   this.getChart(this.state.type, event.target.value as string)
    // };
    var handleChangeQueryUrl = (event: React.ChangeEvent<{ value: unknown }>) => {
      console.log("change= "+this.state.step)
      this.getChart(event.target.value as string)
      // this.getChart(event.target.value as string, this.state.step)
      this.setState({ 
        type: event.target.value
      });
    };
    return (
      <div style={{position: "relative"}}>
        <FormControl className={classes.selItem}>
          {/* <InputLabel id="chartAA" style={{display: "block", lineHeight: "28px"}}>数据</InputLabel> */}
          <Typography className={classes.selType}>通用图表：</Typography>
          <Select
            labelId="chartAA"
            id="chartSelAA"
            value={this.state.type}
            onChange={handleChangeQueryUrl}
            input={<BootstrapInput />}
            style={{width: "90%"}}
          >
            {this.state.queryData.map((type:string) => {
              return(
                <MenuItem value={type}>{type}</MenuItem>
              )
            })}
          </Select>
          {/* <InputLabel style={{top: "initial", lineHeight: "28px"}} id="charta">时长</InputLabel>
          <Select
            labelId="charta"
            id="chartSelA"
            value={this.state.step}
            onChange={handleChange}
            input={<BootstrapInput />}
          >
            <MenuItem value="14">
              <em>1h</em>
            </MenuItem>
            <MenuItem value={"1"}>15min</MenuItem>
            <MenuItem value={"7"}>30min</MenuItem>
            <MenuItem value={"14"}>1h</MenuItem>
            <MenuItem value={"28"}>2h</MenuItem>
          </Select> */}
        </FormControl>
        {this.state.open ? (
        <div className={classes.alert}>
          <Collapse in={this.state.open} className={classes.alertPop}>
            <Alert severity="error" style={{padding: "0 16px"}}
              action={
                <IconButton
                  aria-label="close"
                  color="inherit"
                  size="small"
                  onClick={() => {
                    this.setOpen(false);
                  }}
                >
                  <CloseIcon fontSize="inherit" />
                </IconButton>
              }>
              {this.state.dataWarn}
            </Alert>
          </Collapse>
        </div>
        ):(
        <ReactEcharts
          ref="chart"
          option={this.getOption()}
          className={classes.chart}/>
        )}
      </div>
    );
  }
};
// const mapDispatchToProps = (dispatch:any) => {
//   return {
//     timeConvert: (stamp:any) => dispatch(timeConvert(stamp)),
//     beforeNowtimeByMinu: (min:any) => dispatch(beforeNowtimeByMinu(min)),
//   }
//   }
export default withStyles(styles)(ChartA)